{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Running attribute inference attacks on regression models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial we will show how to run a black-box attribute inference attack on a regression model. This will be demonstrated on the diabetes dataset from scikitlearn (https://scikit-learn.org/stable/datasets/toy_dataset.html#diabetes-dataset). "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attacking a categorical feature\n",
    "We start by trying to infer the 'sex' feature, which is a binary feature."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "sys.path.insert(0, os.path.abspath('..'))\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "from art.utils import load_diabetes\n",
    "\n",
    "(x_train, y_train), (x_test, y_test), _, _ = load_diabetes(test_set=0.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Train MLP model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Base model score:  -0.053305975661749994\n"
     ]
    }
   ],
   "source": [
    "from sklearn.tree import DecisionTreeRegressor\n",
    "from art.estimators.regression.scikitlearn import ScikitlearnRegressor\n",
    "\n",
    "model = DecisionTreeRegressor()\n",
    "model.fit(x_train, y_train)\n",
    "art_regressor = ScikitlearnRegressor(model)\n",
    "\n",
    "print('Base model score: ', model.score(x_test, y_test))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attack\n",
    "### Black-box attack\n",
    "The black-box attack basically trains an additional classifier (called the attack model) to predict the attacked feature's value from the remaining n-1 features as well as the original (attacked) model's predictions.\n",
    "#### Train attack model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from art.attacks.inference.attribute_inference import AttributeInferenceBlackBox\n",
    "\n",
    "attack_train_ratio = 0.5\n",
    "attack_train_size = int(len(x_train) * attack_train_ratio)\n",
    "attack_x_train = x_train[:attack_train_size]\n",
    "attack_y_train = y_train[:attack_train_size]\n",
    "attack_x_test = x_train[attack_train_size:]\n",
    "attack_y_test = y_train[attack_train_size:]\n",
    "\n",
    "attack_feature = 1  # sex\n",
    "\n",
    "# get original model's predictions\n",
    "attack_x_test_predictions = np.array([np.argmax(arr) for arr in art_regressor.predict(attack_x_test)]).reshape(-1,1)\n",
    "# only attacked feature\n",
    "attack_x_test_feature = attack_x_test[:, attack_feature].copy().reshape(-1, 1)\n",
    "# training data without attacked feature\n",
    "x_test_for_attack = np.delete(attack_x_test, attack_feature, 1)\n",
    "\n",
    "bb_attack = AttributeInferenceBlackBox(art_regressor, attack_feature=attack_feature)\n",
    "\n",
    "# train attack model\n",
    "bb_attack.fit(attack_x_train)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Infer sensitive feature and check accuracy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.6126126126126126\n"
     ]
    }
   ],
   "source": [
    "# get inferred values\n",
    "values = [-0.88085106,  1.]\n",
    "inferred_train_bb = bb_attack.infer(x_test_for_attack, pred=attack_x_test_predictions, values=values)\n",
    "# check accuracy\n",
    "train_acc = np.sum(inferred_train_bb == np.around(attack_x_test_feature, decimals=8).reshape(1,-1)) / len(inferred_train_bb)\n",
    "print(train_acc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This means that for 74% of the training set, the attacked feature is inferred correctly using this attack.\n",
    "Now let's check the precision and recall:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0.5816326530612245, 0.9661016949152542)\n"
     ]
    }
   ],
   "source": [
    "def calc_precision_recall(predicted, actual, positive_value=1):\n",
    "    score = 0  # both predicted and actual are positive\n",
    "    num_positive_predicted = 0  # predicted positive\n",
    "    num_positive_actual = 0  # actual positive\n",
    "    for i in range(len(predicted)):\n",
    "        if predicted[i] == positive_value:\n",
    "            num_positive_predicted += 1\n",
    "        if actual[i] == positive_value:\n",
    "            num_positive_actual += 1\n",
    "        if predicted[i] == actual[i]:\n",
    "            if predicted[i] == positive_value:\n",
    "                score += 1\n",
    "    \n",
    "    if num_positive_predicted == 0:\n",
    "        precision = 1\n",
    "    else:\n",
    "        precision = score / num_positive_predicted  # the fraction of predicted “Yes” responses that are correct\n",
    "    if num_positive_actual == 0:\n",
    "        recall = 1\n",
    "    else:\n",
    "        recall = score / num_positive_actual  # the fraction of “Yes” responses that are predicted correctly\n",
    "\n",
    "    return precision, recall\n",
    "    \n",
    "print(calc_precision_recall(inferred_train_bb, np.around(attack_x_test_feature, decimals=8), positive_value=1.))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To verify the significance of these results, we now run a baseline attack that uses only the remaining features to try to predict the value of the attacked feature, with no use of the model itself."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.6666666666666666\n"
     ]
    }
   ],
   "source": [
    "from art.attacks.inference.attribute_inference import AttributeInferenceBaseline\n",
    "\n",
    "baseline_attack = AttributeInferenceBaseline(attack_feature=attack_feature)\n",
    "\n",
    "# train attack model\n",
    "baseline_attack.fit(attack_x_train)\n",
    "# infer values\n",
    "inferred_train_baseline = baseline_attack.infer(x_test_for_attack, values=values)\n",
    "# check accuracy\n",
    "baseline_train_acc = np.sum(inferred_train_baseline == np.around(attack_x_test_feature, decimals=8).reshape(1,-1)) / len(inferred_train_baseline)\n",
    "print(baseline_train_acc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, the black-box attack does significantly better than the baseline."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Attacking a numerical feature\n",
    "Now we will try to infer the bmi level feature."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "54.80737471036833\n"
     ]
    }
   ],
   "source": [
    "attack_feature = 3  # bmi\n",
    "\n",
    "# only attacked feature\n",
    "attack_x_test_feature = attack_x_test[:, attack_feature].copy().reshape(-1, 1)\n",
    "# training data without attacked feature\n",
    "x_test_for_attack = np.delete(attack_x_test, attack_feature, 1)\n",
    "\n",
    "bb_attack = AttributeInferenceBlackBox(art_regressor, attack_feature=attack_feature)\n",
    "\n",
    "# train attack model\n",
    "bb_attack.fit(attack_x_train)\n",
    "\n",
    "inferred_train_bb = bb_attack.infer(x_test_for_attack, pred=attack_x_test_predictions)\n",
    "# check MSE\n",
    "train_acc = np.sum((attack_x_test_feature - inferred_train_bb) ** 2) / len(inferred_train_bb)\n",
    "print(train_acc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "67.66769489356126\n"
     ]
    }
   ],
   "source": [
    "baseline_attack = AttributeInferenceBaseline(attack_feature=attack_feature)\n",
    "\n",
    "# train attack model\n",
    "baseline_attack.fit(attack_x_train)\n",
    "# infer values\n",
    "inferred_train_baseline = baseline_attack.infer(x_test_for_attack)\n",
    "# check MSE\n",
    "baseline_train_acc = np.sum((attack_x_test_feature - inferred_train_baseline) ** 2) / len(inferred_train_baseline)\n",
    "print(baseline_train_acc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The attack succeeds better than the baseline (a lower MSE means higher accuracy)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
